package com.yeguang.LbsApp.baidu.api;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.yeguang.LbsApp.baidu.common.BaiduApiConfig;
import com.yeguang.LbsApp.baidu.model.DirectionApi.BusDirectionObject;

@Component("WebSvcDirectionAPI")
public class WebSvcDirectionAPI {
	@Autowired
	BaiduApiConfig mApiConfig;
	
    public String getBusInfo(String srcAddr, String dstAddr, String city){
    	
    	String url = "http://api.map.baidu.com/direction/v1?mode=transit&origin="+
    			srcAddr +"&destination=" + 
    			dstAddr +"&region=" + 
    			city    + "&output=json&ak=" + mApiConfig.getApiKey();
    	
    	System.out.print(url);
    	
    	RequestConfig config = RequestConfig.custom()
    			.setConnectionRequestTimeout(mApiConfig.getConnectTimeout())
    			.setConnectTimeout(mApiConfig.getConnectTimeout())
    			.setSocketTimeout(mApiConfig.getConnectTimeout()).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        HttpGet get = new HttpGet(url);
        try {
            CloseableHttpResponse r = client.execute(get);
            if (HttpStatus.SC_OK == r.getStatusLine().getStatusCode()) {
            	String body = EntityUtils.toString(r.getEntity(), Charset.forName("UTF-8"));
            	BusDirectionObject obj = JSON.parseObject(body, BusDirectionObject.class);
            	
            	return obj.getType() == 1?obj.getFuzzyResult().toString():"error";
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
            	e.printStackTrace();
            }
        }
        return "";
    }
}
